import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';
import 'package:x3_business_core/business_customer/page/business_customer_details_edit.dart';
import 'package:x3_business_core/business_customer/less_components/business_customer_item_avatar.dart';
import 'package:x3_business_core/business_customer/less_components/business_customer_details_wx_icon.dart';

class BusinessCustomerDetailsHeader extends StatefulWidget {
  BusinessCustomerDetailsHeader({Key key, @required this.vipId, @required this.editCallback}) : super(key: key);

  final String vipId;

  final Function editCallback;

  @override
  _BusinessCustomerDetailsHeaderState createState() => _BusinessCustomerDetailsHeaderState();
}

class _BusinessCustomerDetailsHeaderState extends State<BusinessCustomerDetailsHeader> {
  String _attentionState;

  @override
  Widget build(BuildContext context) {
    return BaseCardComponent(
      child: BaseScreenRefreshComponent(
        request: new BaseScreenRequestModel('/vip/customer/query/customerdetail/{vipId}', method: BaseHttpMethodEnum.GET, params: {'vipId': widget.vipId}),
        controller: new BaseFutureController(),
        builder: (BaseHttpResultModel result) {
          return _buildMainScaffold(context, result.data);
        },
      ),
    );
  }

  Widget _buildMainScaffold(BuildContext context, dynamic data) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            BusinessCustomerItemAvatar(data: data),
            SizedBox(width: 8.0),
            Expanded(child: _buildVipContentWidget(context, data)),
          ],
        ),
        _buildVipBaseInformationRow(data),
      ],
    );
  }

  Widget _buildVipContentWidget(BuildContext context, dynamic data) {
    String gradeName = BaseUtils.getKeyData(data, 'gradeName').toString();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _buildVipNameWidget(data, context),
            _buildPerfectInformationWidget(data, context),
          ],
        ),
        SizedBox(height: 8.0),
        Row(
          children: [Text(gradeName, style: Theme.of(context).textTheme.subtitle1.copyWith(color: Color(0xFFBF9C4F))), BusinessCustomerDetailsWxIcon(item: data)],
        )
      ],
    );
  }

  Widget _buildVipNameWidget(dynamic data, BuildContext context) {
    String vipName = BaseUtils.getKeyData(data, 'vipName').toString();
    String attention = _attentionState ?? BaseUtils.getKeyData(data, 'attention').toString();
    String attentionText = attention == 'true' ? '已关注' : '+ 关注';
    Color borderColor = attention == 'true' ? Theme.of(context).textTheme.subtitle2.color : Theme.of(context).textTheme.bodyText1.color;
    return Row(
      children: [
        Text(vipName, style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 13.0)),
        SizedBox(width: 4.0),
        InkWell(
          onTap: () => _attention(attention),
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 1.0),
            decoration: BoxDecoration(border: Border.all(width: 0.5, color: borderColor), borderRadius: BorderRadius.circular(10.0)),
            child: Text(attentionText, style: Theme.of(context).textTheme.bodyText2.copyWith(color: borderColor, fontSize: 11.0)),
          ),
        ),
      ],
    );
  }

  void _attention(String attention) async {
    String service = attention == 'true' ? '/vip/keyuser/noheed/{vipId}' : '/vip/keyuser/heed/{vipId}';
    String hintText = attention == 'true' ? '正在取消关注' : '正在设置为关注';
    BaseComponentUtils.showLoadingDialog(context, hint: hintText);
    BaseHttpResultModel result = await dioUtil.fetch(service, method: BaseHttpMethodEnum.GET, params: {'vipId': widget.vipId});
    BaseComponentUtils.hideLoadingDialog(context);
    if (result.success == true) {
      setState(() {
        _attentionState = (attention != 'true').toString();
      });
      widget.editCallback();
    }
  }

  Widget _buildPerfectInformationWidget(dynamic data, BuildContext context) {
    return InkWell(
      onTap: () => _goVipInitiationInformationEditScreen(data),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('完善资料', style: Theme.of(context).textTheme.subtitle2.copyWith(color: Color(0xFFCCCCCC))),
          Container(margin: const EdgeInsets.only(left: 4.0), width: 4.0, height: 4.0, decoration: BoxDecoration(color: Colors.red, borderRadius: BorderRadius.circular(2.0))),
          BaseComponentUtils.buildListViewRightIcon(context),
        ],
      ),
    );
  }

  _goVipInitiationInformationEditScreen(dynamic data) {
    String vipId = BaseUtils.getKeyData(data, 'vipId').toString();
    BaseRouterUtil.getInstance().pushNamed(BusinessCustomerDetailsEdit.sName, arguments: {'vipId': vipId});
  }

  Widget _buildVipBaseInformationRow(dynamic data) {
    return BaseScreenRefreshComponent(
      request: BaseScreenRequestModel('/vip/customer/query/customerdetail/{vipId}', method: BaseHttpMethodEnum.GET),
      controller: BaseFutureController(),
      builder: (BaseHttpResultModel result) {
        List<String> rowItems = ['vipScore', 'vipPurse', 'vipOrder', 'couponNum'];
        List<BaseHttpResponseModel> responses = BaseTransformUtil.transformToListResponseData(result.data);
        List<BaseHttpResponseModel> showResponses = responses.where((element) => rowItems.contains(element.fieldName)).toList();
        return Padding(padding: const EdgeInsets.only(top: 12.0), child: _buildBaseInformationRow(showResponses, data));
      },
      serviceType: BaseScreenRefreshServiceType.Response,
    );
  }

  Widget _buildBaseInformationRow(List<BaseHttpResponseModel> responses, dynamic dataSource) {
    return BaseInformationRow(
      list: responses,
      builder: (BaseHttpResponseModel response) {
        String value = BaseUtils.getKeyData(dataSource, response.fieldName).toString();
        return BaseInformationRowItem(
          onTap: () => _buildBaseInformationRowItemPress(response, dataSource),
          isAnimation: true,
          text: response.name,
          numberText: value,
        );
      },
    );
  }

  void _buildBaseInformationRowItemPress(BaseHttpResponseModel response, dynamic dataSource) {
    String vipId = BaseUtils.getKeyData(dataSource, 'vipId').toString();
    Map<String, dynamic> params = {'vipId': vipId};
    BaseRouterUtil.getInstance().pushNamed(response.webUrl, arguments: params );
  }

}
